#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2022/4/7 16:29'
# software: PyCharm


import django_filters
from django.db.models import Q

from .models import Goods


class GoodsFilter(django_filters.rest_framework.FilterSet):
    """
    商品的过滤类
    """
    # 配置过滤条件，models中Goods类中的shop_price(价格)字段
    price_min = django_filters.NumberFilter(field_name='shop_price', help_text="最低价格", lookup_expr='gte')
    price_max = django_filters.NumberFilter(field_name='shop_price', help_text="最高价格", lookup_expr='lte')
    # 过滤条件不能通过配置实现时，通过自定义过滤方法top_category_filter来实现
    top_category = django_filters.NumberFilter(method='top_category_filter', help_text="第一类别下面所有商品")

    # 查找类别下面所有的商品,value是前端url中传递过来的类别ID
    def top_category_filter(self, queryset, name, value):  # 自定义过滤方法，里面是自定义过滤条件
        """
        :param queryset: 默认参数，models.py中Goods的对象queryset
        :param name: 默认参数
        :param value: 默认参数,url传递过来的商品类别ID
        :return:
        """
        return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
            category__parent_category__parent_category_id=value))

    class Meta:
        model = Goods
        fields = ['price_min', 'price_max', 'is_hot', 'is_new']













# class GoodsFilter(django_filters.rest_framework.FilterSet):
#     """
#     商品的过滤类
#     """
#     # 配置过滤条件，models中Goods类中的shop_price(价格)字段
#     pricemin = django_filters.NumberFilter(name='shop_price', help_text="最低价格", lookup_expr='gte')
#     pricemax = django_filters.NumberFilter(name='shop_price', help_text="最高价格", lookup_expr='lte')
#     # 过滤条件不能通过配置实现时，通过自定义过滤方法top_category_filter来实现
#     top_category = django_filters.NumberFilter(method='top_category_filter', help_text="第一类别下面所有商品")
#
#     # 查找类别下面所有的商品,value是前端url中传递过来的类别ID
#     def top_category_filter(self, queryset, value):  # 自定义过滤方法，里面是自定义过滤条件
#         """
#         :param queryset: 默认参数，models.py中Goods的对象queryset
#         :param name: 默认参数
#         :param value: 默认参数,url传递过来的商品类别ID
#         :return:
#         """
#         return queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
#             category__parent_category__parent_category_id=value))
#
#     class Meta:
#         model = Goods
#         fields = ['pricemin', 'pricemax', 'is_hot', 'is_new']


